package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.mongo.VoiceApi;
import com.tanhua.model.mongo.Voice;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.Random;

@DubboService
public class VoiceApiImpl implements VoiceApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public void save(Voice voice) {
        mongoTemplate.save(voice);
    }
    //随机获取一条语言
    @Override
    public Voice rundomPeachblossom(Long userId) {
        //查询语音总数
        Query query = Query.query(Criteria.where("status").is(1).and("userId").nin(userId));
        List<Voice> voices = mongoTemplate.find(query, Voice.class);
        if(CollUtil.isEmpty(voices)){
            return null;
        }
        Random random = new Random();
        int i = random.nextInt(voices.size());
        return voices.get(i);
    }

    @Override
    public void update(Voice voice) {
        mongoTemplate.save(voice);
    }
}
